package zk.weart.core.aliyun.sms;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zk.weart.core.aliyun.AliyunConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zjk
 * @Description:
 * @Date 2022/5/11 15:19
 **/
@Component
@Slf4j
public class AliSmsUtil {

    @Autowired
    AliyunConfig aliyunConfig;

    public Client createClient() throws Exception {

        Map<String,Object> map = new HashMap<>();
        map.put("accessKeyId",this.aliyunConfig.getAccessKeyId());
        map.put("accessKeySecret",this.aliyunConfig.getAccessKeySecret());
        map.put("endpoint",this.aliyunConfig.getSmsConfig().getEndpoint());

        Config config = Config.build(map);
        return new Client(config);
    }

    /**
     * 功能描述: 短信发送
     * @author zkj
     * @date 2022/5/12
     * @param phoneNumbers
     * @param templateCode
     * @param templateParam
     * @return java.lang.Boolean
     */

    public Boolean sendSms(String phoneNumbers,String templateCode, String templateParam){
        try {

            log.info("短信发送 phoneNumbers:{} templateCode:{} templateParam：{} ",
                    phoneNumbers,templateCode,templateParam);
            Client client = this.createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(phoneNumbers);
            sendSmsRequest.setTemplateCode(templateCode);
            if(StringUtils.isNotBlank(templateParam)){
                sendSmsRequest.setTemplateParam(templateParam);
            }
            sendSmsRequest.setSignName(this.aliyunConfig.getSmsConfig().getSignName());
            SendSmsResponse sendSmsResponse =  client.sendSms(sendSmsRequest);
            log.info("短信结果:{}", JSON.toJSON(sendSmsResponse));
            SendSmsResponseBody body  = sendSmsResponse.getBody();
            if("OK.".equals(body.getCode())){
                log.info("短信发送成功");
                return  true;
            }
        }catch (Exception e){
            log.error("阿里云短息发送失败",e);
        }

        return  false;

    }




}
